<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelists" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand" label="扩展内容">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom',i1===0?'bdtop':'','vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级 -->
              <el-col :span="19">
                <!-- 通过for循环， 嵌套渲染二级权限 -->
                <el-row
                  :class="[i2===0?'':'bdtop',,'vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      :class="['bdbottom',i3===0?'bdtop':'']"
                      v-for="(item3,i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
                    {{scope.row}}
            </pre>-->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操纵">
          <template slot-scope="scope" width="300px">
            <!-- 修改按钮 -->
            <el-tooltip effect="dark" content="修改列表" placement="top" :enterable="false">
              <el-button
                type="primary"
                @click="Edit(scope.row.id)"
                icon="el-icon-edit"
                size="mini"
              >编辑</el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip effect="dark" content="删除列表" placement="top" :enterable="false">
              <el-button
                type="danger"
                @click="removeUserById(scope.row.id)"
                icon="el-icon-delete"
                size="mini"
              >删除</el-button>
            </el-tooltip>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                @click="showSetRightDialog(scope.row)"
                size="mini"
              >分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加用户" @close="addDialogClosed" :visible.sync="addDialogVisible" width="50%">
      <!-- 内容主体区域 -->
      <el-form :model="rolesFrom" ref="ruleFormRef" label-width="70px">
        <el-form-item label="角色ID">
          <el-input v-model="rolesEdit.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="rolesFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="mobile">
          <el-input v-model="rolesFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="showSetRightDialogVisible"
      width="30%"
      @close="setRightclose"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightslist"
        :props="treeProps"
        :default-checked-keys="defKeys"
        show-checkbox
        node-key="id"
        default-expand-all
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 角色编辑框 -->
    <el-dialog title="修改" @close="editFromClosed" :visible.sync="setRoleVisible" width="30%">
      <el-form :model="rolesEdit" ref="editFormRef" label-width="70px">
        <el-form-item label="角色ID">
          <el-input v-model="rolesEdit.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="rolesEdit.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="mobile">
          <el-input v-model="rolesEdit.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 所有角色列表数据
      rolelists: [],
      // 控制分配权限对话框的显示与隐藏
      showSetRightDialogVisible: false,
      // 所有权限的数据
      rightslist: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点Id值数组
      defKeys: [],
      // 当前即将分配权限大的角色id
      roleId: '',
      setRoleVisible: false,
      addDialogVisible: false,
      rolesEdit: [],
      rolesFrom: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取列表失败')
      }
      this.rolelists = res.data
      // console.log(this.rolelists)
    },
    // 根据Id删除对应的权限
    async removeRightById (role, rightId) {
      // 有弹窗提示用户是否要删除
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 如果确认删除，则返回值为字符串
      // 如果用户取消删除，返回字符串cancel
      // console.log(confirmRes)
      if (confirmRes !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      // console.log(res)
      if (res.meta.status !== 200) { return this.$message.error('删除权限失败') }
      this.$message.success('删除权限成功')

      //   this.getRolesList()
      role.children = res.data
    },
    async  showSetRightDialog (role) {
      this.roleId = role.id
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res)

      if (res.meta.status !== 200) { return this.$message.error('获取权限列表失败') }
      // 把获取到的权限数据数据保存到  data在rightslist列表
      this.rightslist = res.data
      // console.log(this.rightslist)
      // 递归获取三级节点的id地址
      this.getLeafKeys(role, this.defKeys)
      this.showSetRightDialogVisible = true
    },
    // 通过递归形式,获取角色下所有三级权限id,并保存到defKeys数组中
    getLeafKeys (node, arr) {
      // 如果当前node节点不包含children属性,则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightclose () {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRight () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      console.log(res)
      if (res.meta.status !== 200) { return this.$message.error('分配权限列表失败') }
      this.$message.success('分配权限列表成功')
      this.getRolesList()
      this.showSetRightDialogVisible = false
    },
    // 编辑提交角色
    async Edit (roleId) {
      // console.log(roleId)
      const { data: res } = await this.$http.get('roles/' + roleId)

      if (res.meta.status !== 200) return this.$message.error('角色获取失败')
      this.rolesEdit = res.data
      // console.log(this.rolesEdit)
      this.setRoleVisible = true
    },
    // 编辑用户表单关闭重置
    editFromClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击按钮，添加新用户
    addRoles () {
      // 点击确定按钮，添加新用户
      // 调用validate进行表单验证
      this.$refs.ruleFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整角色信息')
        // 发送请求完成添加用户的操作
        const { data: res } = await this.$http.post('roles', this.rolesFrom)
        // console.log(res)
        // 判断如果添加失败，就做提示
        if (res.meta.status !== 201) { return this.$message.error('添加角色失败') }
        // 添加成功的提示
        this.$message.success('添加角色成功')
        // 关闭对话框
        this.addDialogVisible = false
        // 重新请求最新的数据
        this.getRolesList()
      })
    },
    addDialogClosed () {
      this.$refs.ruleFormRef.resetFields()
    },
    editRoles () {
      // 点击确定按钮，添加更新角色
      // 调用validate进行表单验证
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整用户信息')
        // 发送请求完成添加用户的操作
        const { data: res } = await this.$http.put('roles/' + this.rolesEdit.roleId, { roleName: this.rolesEdit.roleName, roleDesc: this.rolesEdit.roleDesc })
        // console.log(res)
        // 判断如果添加失败，就做提示
        if (res.meta.status !== 200) { return this.$message.error('更新角色失败') }
        // 关闭对话框
        this.setRoleVisible = false
        // 重新请求最新的数据
        this.getRolesList()
        // 添加成功的提示
        this.$message.success('修改角色成功')
      })
    },
    async removeUserById (roleId) {
      // 弹窗询问用户是否删除数据
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      // 如果确认删除，则返回值为字符串
      // 如果用户取消删除，返回字符串cancel
      // console.log(confirmRes)
      if (confirmRes !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + roleId)
      if (res.meta.status !== 200) { return this.$message.error('删除角色失败') }
      this.$message.success('删除角色成功')
      this.getRolesList()
    }
  }
}
</script>

<style lang="less">
.el-tag{
    margin: 7px;
}
// .bdtop{
//     border:1px solid #eee

// }
// .bdbottom{
//     border-bottom:1px solid #eee
// }
.vcenter{
    display: flex;
    align-items: center;
}
</style>
